package ru.hh.school;

import ru.hh.school.commands.ChatRouter;
import ru.hh.school.logging.StaticLogger;

import java.io.IOException;
import java.io.ObjectInputStream;

public class UserInput implements Runnable {
    private ObjectInputStream stream;
    private ChatRouter router;
    private User user;

    public UserInput(ObjectInputStream stream, User user, ChatRouter router) throws IOException {
        this.stream = stream;
        this.user = user;
        this.router = router;
    }

    public void run() {
        try {
            try {
                while (!Thread.interrupted()) {
                    String message = (String) stream.readObject();
                    router.command(user, message);
                }
            } catch (IOException e) {
                router.command(user, "/quit Disconnected");
            } catch (ClassNotFoundException e) {
                router.command(user, "/quit Wrong protocol");
            } finally {
                try {
                    if (stream != null) {
                        stream.close();
                    }
                } catch (IOException e) {
                    StaticLogger.getLogger().logError(e);
                }
            }
        } catch (InterruptedException e) {
            StaticLogger.getLogger().logError(e);
        }

    }
}
